/**
 * 发送手机验证码
 */
import { sendCode } from '../../../util/code/messageCode';
import { checkPhone } from '../../../model/service/account/phone';
import { getUserInfo } from '../../../model/service/account/userInfo';
import { opType } from '../../../const';
/**
 * type 0 -- 注册， 1 -- 登录, 2 -- 修改东西
 */

export default async function sendPhoneCode(ctx: Context, next: Next): Promise<void> {
  
  const { body } = ctx.request;
  const { phoneNumber, type, username } = body;

  // 注册
  if (Number(type) === opType.register) {
    const result = await checkPhone(phoneNumber);
    if (result.length !== 0) {
      ctx.api.fail(-1, '该手机号已被注册');
      return next();
    }
  } else if (Number(type) === opType.modify) {
    // 修改东西，需要验证是这个用户的手机号才行
    const result = await getUserInfo({ username });
    if (result.length !== 1 || result[0].phoneNumber !== phoneNumber) {
      ctx.api.fail(-1, result.length ? `请使用改用户手机号,手机尾号为 ${result[0].phoneNumber.substr(7, 11)}` : '改用户未注册');
      return next();
    }
  }

  const opt = {
    PhoneNumberSet: [phoneNumber],
  }
  // ctx.api.success({name: 111}, 'sucess');
  try {
    const responseData = await sendCode(opt);
    ctx.api.success(responseData, 'sucess');
  } catch (error) {
    ctx.api.fail(-1, error);
  }

  return next();
}